package com.mmall.concurrency.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mmall.concurrency.example.atomic.AtomicExample3;

@Slf4j
public class SemaphoreExample3 {
	private static Logger log = LoggerFactory.getLogger(AtomicExample3.class);

    private static int threadCount = 20;

    public static void main(String[] args) throws Exception{
        ExecutorService executorService = Executors.newCachedThreadPool();

        final Semaphore semaphore = new Semaphore(3); // 控制同时只能有20个线程访问

        for (int i = 0; i < threadCount; i++) {
            final int threadNumber = i;
            executorService.execute(()->{
                try{
                    // 尝试获得一个许可， 得到许可的可以继续执行，得不到的就会被直接丢弃，不会继续执行了
                    // 这里尝试等5000毫秒，没有获取到丢弃
                    if (semaphore.tryAcquire(5000, TimeUnit.MILLISECONDS)){
                        test(threadNumber);
                        semaphore.release(); // 释放一个许可
                    }
                }catch (Exception e){
                    log.error("exception", e);
                }finally {

                }
            });
        }
        log.info("finish");
        executorService.shutdown(); // 如果线程池不再使用，不要忘记关闭
    }

    private static void test(int threadNumber) throws Exception{
        log.info("{}", threadNumber);
        Thread.sleep(1000);
    }
}

/*

只有三个线程得到了执行，其他线程全被丢弃
15:34:19.024 [pool-1-thread-1] INFO com.mmall.concurrency.example.aqs.SemaphoreExample3 - 0
15:34:19.024 [pool-1-thread-3] INFO com.mmall.concurrency.example.aqs.SemaphoreExample3 - 2
15:34:19.024 [pool-1-thread-2] INFO com.mmall.concurrency.example.aqs.SemaphoreExample3 - 1
15:34:19.024 [main] INFO com.mmall.concurrency.example.aqs.SemaphoreExample3 - finish

* */